package com.test.io.group;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

public class CharServer {
    //定义属性
    private Selector selector;
    private ServerSocketChannel listenChannel ;
    private static final int port = 6667;

    //构造器，初始化工作
    public CharServer(){
        try{
            //得到选择器
            selector=Selector.open();
            //得到ServerSocketChannel
            listenChannel = ServerSocketChannel.open();
            //绑定端口
            listenChannel.socket().bind(new InetSocketAddress(port));
            //设置非阻塞
            listenChannel.configureBlocking(false);
            //注册通道,监听accept事件
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //监听
    public void listen(){
        try {
            //循环监听
            while (true){
                int count = selector.select(2000);
                if(count > 0){
                    //有事件需要处理
                    //遍历得到selectionKey集合
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()){
                        //取出selectionKey
                        SelectionKey key = iterator.next();
                        //监听到accept
                        if(key.isAcceptable()){
                            SocketChannel accept = listenChannel.accept();
                            accept.configureBlocking(false);
                            //注册到selector
                            accept.register(selector,SelectionKey.OP_READ);
                            //提示
                            System.out.println(accept.getRemoteAddress()+" 上线了");
                        }
                        //通道处于可读状态
                        if(key.isReadable()){
                            //处理读
                            readData(key);
                        }

                        //删除当前的key，避免重复处理
                        iterator.remove();
                    }


                }else{
                    System.out.println("等待................");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //读取客户端消息
    private void readData(SelectionKey key){
        //定义socketchannel
        SocketChannel channel = null;
        try {
            //取到关联的channel
            channel = (SocketChannel) key.channel();
            //创建Buffer
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            //channel 读取数据到buffer
            int count = channel.read(buffer);
            //根据count的值进行处理
            if(count > 0){
                //把缓冲区的数据转为字符串
                String s = new String(buffer.array());
                //输出该消息
                System.out.println("from 客户端 :" + s);

                //向其他客户端转发消息，
                sendMsgToClients(s,channel);
            }
        } catch (IOException e) {
            e.printStackTrace();
            try {
                System.out.println(channel.getRemoteAddress() + "离线了。。。。。。。。。");
                //取消注册
                key.cancel();
                //关闭通道
                channel.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    //转发消息给其他客户,需要排除自身
    private void sendMsgToClients(String msg,SocketChannel self){
        System.out.println("服务器转发消息。。。。。。。。。。。。。。。");
        try {
            //遍历seletionkeys
            for(SelectionKey key : selector.keys()){
                //通过key取出对应的 channel
                Channel channel = key.channel();
                //排除自己
                if(channel instanceof  SocketChannel && channel != self){
                    //转型
                    SocketChannel dest = (SocketChannel) channel;
                    //将msg 存储到buffer
                    ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                    //将buffer的数据写入通道
                    ((SocketChannel) channel).write(buffer);
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //创建一个服务器对象
        CharServer server =  new CharServer();
        server.listen();
    }
}
